import mysql from 'mysql2/promise'

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'Lizhiyuan101!',
  database: 'mofang',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  timezone: '+08:00'
}

const pool = mysql.createPool(dbConfig)

// 获取连接
export const getConnection = async () => {
  try {
    const connection = await pool.getConnection()
    return connection
  } catch (error) {
    console.error('数据库连接错误:', error)
    throw error
  }
}

// 执行查询
export const query = async (sql, params = []) => {
  let connection
  try {
    connection = await pool.getConnection()
    const [results] = await connection.execute(sql, params)
    return results
  } catch (error) {
    console.error('查询执行错误:', error)
    throw error
  } finally {
    if (connection) {
      connection.release()
    }
  }
}

export { dbConfig }

// 导出连接池
export default pool 